package com.heying.springbootweb.controller;

import com.heying.springbootweb.entity.Student;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.NoSuchElementException;

@Controller
@RequestMapping("/stu")//一级路径
@Slf4j
public class StudentController {

   private List<Student> students;

   @Value("${upload.path}")
   private String uploadPath;

    {
        students = new ArrayList<>();
        students.add(new Student(1,"1001","aaa",new Date(),0,1,"music sport",1));
        students.add(new Student(2,"1002","bbb",new Date(),1,2,"music java",1));
        students.add(new Student(3,"1003","ccc",new Date(),1,2,"music sport",1));
        students.add(new Student(4,"1004","ddd",new Date(),0,1,"music sport",1));
        students.add(new Student(5,"1005","eee",new Date(),0,0,"java,sport",1));
    }

    @GetMapping("/queryall")
    public String queryAll(Model model){
        model.addAttribute("students",students);
        return "stu/studentlist";//request.getRequestDispatcher("url").forward(request.response)
    }

    @GetMapping("/toadd")
    public String toAdd(Model model){
        model.addAttribute("stu", new Student());
        return "stu/addone";
    }

    @PostMapping("/addone")
    public String addOne(Student stu, @RequestPart("photo")Part photo) throws IOException {
        log.info("stu is {}",stu);
        log.debug("submitName is {}",photo.getSubmittedFileName());
        log.debug("contextType is {}",photo.getContentType());
        log.debug("fileSize is {}",photo.getSize());
        photo.write(uploadPath+File.separator +photo.getSubmittedFileName());
        stu.setId(students.stream().mapToInt(Student::getId).max().orElse(0)+1);
        students.add(stu);
        log.info("stus is {}",students);
        return "main";
    }

    @GetMapping("tomod")
    public String toMod(@RequestParam("id") Integer id,Model model){
        Student student = students.stream()
                .filter(s->s.getId().equals(id)).findFirst().orElse(null);
        if(null ==student){
            throw new NoSuchElementException();
        }
        model.addAttribute("stu", student);
        return "stu/modone";
    }

    @PostMapping("/modone")
    public String modOne(Student stu){
        students.stream().
                filter(s->s.getId().equals(stu.getId())).findFirst().
                ifPresent(s-> BeanUtils.copyProperties(stu,s));
        log.debug("new students is {}",students);

        return "main";
    }
}
